package cn.edu.zut.sunday.utils;

import cn.edu.zut.sunday.base.init.InitDatabaseService;
import cn.edu.zut.sunday.constant.ThreadConfig;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public enum ThreadUtils {
    POOL(Executors.newFixedThreadPool(ThreadConfig.THREAD_NUM));

    private final ExecutorService          pool;
    private final ListeningExecutorService service;

    ThreadUtils(ExecutorService pool) {
        this.pool = pool;
        this.service = MoreExecutors.listeningDecorator(this.pool);
    }

    /**
     * 异步数据导入数据库中
     * @param initDatabaseService 导入数据服务
     * @param successInfo 成功时提示信息
     * @param failInfo 失败时提示信息
     */
    public void submit(InitDatabaseService initDatabaseService,
                        String successInfo, String failInfo) {
        final ListenableFuture<Boolean> future = this.service.submit(
          initDatabaseService::initDatabase);
        Futures.addCallback(future, new FutureCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean result) {
                if (result != null && result) {
                    log.info(successInfo);
                } else {
                    log.error(failInfo);
                }
            }

            @Override
            public void onFailure(@NonNull Throwable t) {
                log.error(failInfo);
                log.error("error info: {}", t.getMessage());
            }
        }, this.pool);
    }
}
